import Vue from 'vue'
import VueResource from 'vue-resource'

Vue.use(VueResource)
export default {
  //获取用户角色

  getRoles: function (cb) {
    var currentUser = AV.User.current();
    if (!currentUser) return cb(false);
    currentUser.getRoles().then(function (roles) {
      console.log(roles)
      var isAdmin = true;
      for (let i = 0; i < roles.length; i++) {
        if (roles[i].toJSON().name === 'teacher') {
          isAdmin = false;
          break
        }
      }
      if (!isAdmin) return cb(false);
      else return cb(true)
    })
  },
  // 获取全部课程
  getAllData: function (cb) {
    var self = this
    this.getRoles(function (result) {
      var subjects = {'song': [], 'music': [], 'read': [], 'play': []}
      if (result === true) {
        self.adminSubLesson(subjects, function (result) {
          cb(result)
        })
      } else {
        self.teacherSubLesson(subjects, function (result) {
          cb(result)
        })
      }
    })
  },
  //获取admin的全部科目课程
  adminSubLesson: function (subjects, cb) {
    var self = this
    var priorityQuery = new AV.Query('Lesson');
    priorityQuery.equalTo('isPublished', true);
    var statusQuery = new AV.Query('Lesson');
    statusQuery.equalTo('isChecked', 1);
    var query = AV.Query.or(priorityQuery, statusQuery);
    query.find().then(function (result) {
      result.forEach(function (key) {
        var subject = key._serverData.subject.id
        var checkedStatus = key.attributes.isChecked
        if (subject === '5a8e908dac502e0032b6225d') {
          subjects.play.push({'name': key.attributes.name, 'id': key.id, 'isChecked': checkedStatus})
          if (checkedStatus == 1) {
            self.getHistoryLesson(key.id, function (result) {
              Vue.http.get(result).then(function (response) {
                subjects.play.push({'name': response.data.name, 'id': response.data.id, 'verstion': 'his'})
                console.log(response)
                // console.log({'name':response.data.name,'id':response.data.id ,'verstion':'his'})
              })
            })
          }
        }
        else if (subject === '5a701c82d50eee00444134b2') {
          subjects.read.push({'name': key.attributes.name, 'id': key.id, 'isChecked': key.attributes.isChecked})
          if (checkedStatus == 1) {
            self.getHistoryLesson(key.id, function (result) {
              Vue.http.get(result).then(function (response) {
                subjects.read.push({'name': response.data.name, 'id': response.data.id, 'verstion': 'his'})
                console.log(response)
              })
            })
          }
        }
        else if (subject === '5a741bcb2f301e003be904ed') {
          subjects.music.push({'name': key.attributes.name, 'id': key.id, 'isChecked': key.attributes.isChecked})
          if (checkedStatus == 1) {
            self.getHistoryLesson(key.id, function (result) {
              Vue.http.get(result).then(function (response) {
                subjects.music.push({'name': response.data.name, 'id': response.data.id, 'verstion': 'his'})
                console.log(response.data.name)
              })
            })
          }
        }
        else {
          subjects.song.push({'name': key.attributes.name, 'id': key.id, 'isChecked': key.attributes.isChecked})
          if (checkedStatus == 1) {
            self.getHistoryLesson(key.id, function (result) {
              Vue.http.get(result).then(function (response) {
                subjects.song.push({'name': response.data.name, 'id': response.data.id, 'verstion': 'his'})
                console.log(response.data.tags)
              })
            })
          }
        }
      })
      cb(subjects)
    }, function (err) {
      console.log(err)
    })
  },
  //获取老师的全部科目课程
  //获取老师的全部课程
  teacherSubLesson: function (subjects, cb) {
    var self = this
    var query = new AV.Query('Lesson')
    query.equalTo('isPublished', true)
    query.find().then(function (result) {
      result.forEach(function (key) {
        if (key.attributes.isChecked === 3 || key.attributes.isChecked === 0) {
          var subject = key._serverData.subject.id
          if (subject == '5a8e908dac502e0032b6225d') {
            subjects.play.push({'name': key.attributes.name, 'id': key.id})
          }
          else if (subject == '5a701c82d50eee00444134b2') {
            subjects.read.push({'name': key.attributes.name, 'id': key.id})
          }
          else if (subject == '5a741bcb2f301e003be904ed') {
            subjects.music.push({'name': key.attributes.name, 'id': key.id})
          }
          else {
            subjects.song.push({'name': key.attributes.name, 'id': key.id})
          }
        } else if (key.attributes.isChecked === 1 || key.attributes.isChecked === 2) {
          var lessonId = key.id
          self.getHistoryLesson(lessonId, function (result) {
            Vue.http.get(result).then(function (response) {
              var subject = response.data.subjectId
              if (subject == '5a8e908dac502e0032b6225d') {
                subjects.play.push({'name': response.data.name, 'id': response.data.id, 'verstion': 'his'})
              }
              else if (subject == '5a701c82d50eee00444134b2') {
                subjects.read.push({'name': response.data.name, 'id': response.data.id, 'verstion': 'his'})
              }
              else if (subject == '5a741bcb2f301e003be904ed') {
                subjects.music.push({'name': response.data.name, 'id': response.data.id, 'verstion': 'his'})
              }
              else {
                subjects.song.push({'name': response.data.name, 'id': response.data.id, 'verstion': 'his'})
              }
            }, function (err) {

            })
          })

        }
      })
      cb(subjects)
    }, function (err) {
      console.log(err)
    })
  },
  //获取全部领域
  getAllTag: function (cb) {
    var self = this
    self.getRoles(function (result) {
      var tag = {'healthy': [], 'language': [], 'art': [], 'science': [], 'social': []}
      if (result === true) {
        self.adminTagLesson(tag, function (result) {
          cb(result)
        })
      } else {
        self.teacherTagLesson(tag, function (result) {
          cb(result)
        })
      }
    })
  },
  //获取admin的领域全部课程 整理数组 result[]
  //cd回调函数
  adminTagLesson: function (tag, cb) {
    var self = this
    var priorityQuery = new AV.Query('Lesson');
    priorityQuery.equalTo('isPublished', true);
    var statusQuery = new AV.Query('Lesson');
    statusQuery.equalTo('isChecked', 1);
    var query = AV.Query.or(priorityQuery, statusQuery);
    query.find().then(function (result) {
      result.forEach(function (key) {
        var keyTags = key.attributes.tags
        var subject = key._serverData.subject.id
        var checkedStatus = key.attributes.isChecked
        keyTags.forEach(function (item) {
          if (item == "domain.语言") {
            tag.language.push({
              'name': key.attributes.name,
              'id': key.id,
              'subject': self.judgeSubject(subject),
              'isChecked': checkedStatus
            })
            if (checkedStatus == 1) {
              self.getHistoryLesson(key.id, function (result) {
                Vue.http.get(result).then(function (response) {
                  tag.language.push({
                    'name': response.data.name,
                    'id': response.data.id,
                    'subject': self.judgeSubject(subject),
                    'verstion': 'his'
                  })
                })
              })
            }
          }
          if (item == "domain.艺术") {
            tag.art.push({
              'name': key.attributes.name,
              'id': key.id,
              'subject': self.judgeSubject(subject),
              'isChecked': checkedStatus
            })
            if (checkedStatus == 1) {
              self.getHistoryLesson(key.id, function (result) {
                Vue.http.get(result).then(function (response) {
                  tag.art.push({
                    'name': response.data.name,
                    'id': response.data.id,
                    'subject': self.judgeSubject(subject),
                    'verstion': 'his'
                  })
                })
              })
            }
          }
          if (item == "domain.科学") {
            tag.science.push({
              'name': key.attributes.name,
              'id': key.id,
              'subject': self.judgeSubject(subject),
              'isChecked': checkedStatus
            })
            if (checkedStatus == 1) {
              self.getHistoryLesson(key.id, function (result) {
                Vue.http.get(result).then(function (response) {
                  tag.science.push({
                    'name': response.data.name,
                    'id': response.data.id,
                    'subject': self.judgeSubject(subject),
                    'verstion': 'his'
                  })
                })
              })
            }
          }
          if (item == "domain.健康") {
            tag.healthy.push({
              'name': key.attributes.name,
              'id': key.id,
              'subject': self.judgeSubject(subject),
              'isChecked': checkedStatus
            })
            if (checkedStatus == 1) {
              self.getHistoryLesson(key.id, function (result) {
                Vue.http.get(result).then(function (response) {
                  tag.healthy.push({
                    'name': response.data.name,
                    'id': response.data.id,
                    'subject': self.judgeSubject(subject),
                    'verstion': 'his'
                  })
                })
              })
            }
          }
          if (item == "domain.社会") {
            tag.social.push({
              'name': key.attributes.name,
              'id': key.id,
              'subject': self.judgeSubject(subject),
              'isChecked': checkedStatus
            })
            if (checkedStatus == 1) {
              self.getHistoryLesson(key.id, function (result) {
                Vue.http.get(result).then(function (response) {
                  tag.social.push({
                    'name': response.data.name,
                    'id': response.data.id,
                    'subject': self.judgeSubject(subject),
                    'verstion': 'his'
                  })
                })
              })
            }
          }
        })
      })
      cb(tag)
    }, function (err) {
      console.log(err)
    })
  },
  //获取老师的领域全部课程
  teacherTagLesson: function (tag, cb) {
    var self = this;
    var query = new AV.Query('Lesson')
    query.equalTo('isPublished', true)
    query.find().then(function (result) {
      result.forEach(function (key) {
        if (key.attributes.isChecked === 3 || key.attributes.isChecked === 0) {
          var keyTags = key.attributes.tags
          var subject = key._serverData.subject.id
          keyTags.forEach(function (item) {
            if (item == "domain.语言") {
              tag.language.push({'name': key.attributes.name, 'id': key.id, 'subject': self.judgeSubject(subject)})
            }
            if (item == "domain.艺术") {
              tag.art.push({'name': key.attributes.name, 'id': key.id, 'subject': self.judgeSubject(subject)})
            }
            if (item == "domain.科学") {
              tag.science.push({'name': key.attributes.name, 'id': key.id, 'subject': self.judgeSubject(subject)})
            }
            if (item == "domain.健康") {
              tag.healthy.push({'name': key.attributes.name, 'id': key.id, 'subject': self.judgeSubject(subject)})
            }
            if (item == "domain.社会") {
              tag.social.push({'name': key.attributes.name, 'id': key.id, 'subject': self.judgeSubject(subject)})
            }
          })
        }
        else if (key.attributes.isChecked === 1 || key.attributes.isChecked === 2) {
          //todo
          //获取历史版本
          var lessonId = key.id;
          self.getHistoryLesson(lessonId, function (result) {
            Vue.http.get(result).then(function (response) {
              var keyTags = response.data.tags
              var subject = response.data.subjectId;
              keyTags.forEach(function (item) {
                if (item == "domain.语言") {
                  tag.language.push({
                    'name': response.data.name,
                    'id': response.data.id,
                    'subject': self.judgeSubject(subject),
                    'verstion': 'his'
                  })
                }
                if (item == "domain.艺术") {
                  tag.art.push({
                    'name': response.data.name,
                    'id': response.data.id,
                    'subject': self.judgeSubject(subject),
                    'verstion': 'his'
                  })
                }
                if (item == "domain.科学") {
                  tag.science.push({
                    'name': response.data.name,
                    'id': response.data.id,
                    'subject': self.judgeSubject(subject),
                    'verstion': 'his'
                  })
                }
                if (item == "domain.健康") {
                  tag.healthy.push({
                    'name': response.data.name,
                    'id': response.data.id,
                    'subject': self.judgeSubject(subject),
                    'verstion': 'his'
                  })
                }
                if (item == "domain.社会") {
                  tag.social.push({
                    'name': response.data.name,
                    'id': response.data.id,
                    'subject': self.judgeSubject(subject),
                    'verstion': 'his'
                  })
                }
              })
            }, function (err) {

            })
          })
        }

      });
      cb(tag)
    }, function (err) {
      console.log(err)
    })
  },
  //判断领域课程属于那个科目
  judgeSubject: function (subject) {
    if (subject == '5a8e908dac502e0032b6225d') {
      return 'play'
    }
    if (subject == '5a701c82d50eee00444134b2') {
      return 'read'
    }
    if (subject == '5a741bcb2f301e003be904ed') {
      return 'music'
    } else {
      return 'song'
    }
  },
  //获取历史版本
  getHistoryLesson: function (lessonId, cb) {
    var startDateQuery = new AV.Query('LessonSnapshot');
    startDateQuery.equalTo('lessonId', lessonId)
    var endDateQuery = new AV.Query('LessonSnapshot');
    startDateQuery.equalTo('isChecked', 3);
    var query = AV.Query.and(startDateQuery, endDateQuery);
    query.find().then(function (result) {

      if (result.length == 1) {
        console.log(result[0].toJSON().manifest_json.url)
        cb(result[0].toJSON().manifest_json.url)
      } else if (result.length > 1) {
        var version = 1
        var lesson = ''
        result.forEach(function (item) {
          if (item.attributes.version_code > version) {
            version = item.attributes.version_code
            lesson = item.toJSON().manifest_json.url
          }
        })
        console.log(lesson)
        cb(lesson)
      } else {
        cb()
      }

    }, function (e) {
      console.log(e)
      cb()
    })
  },
  //获取喜欢课程获取到当前用户喜欢的课程
  getLikeLesson: function (cb) {
    var self = this
    var currentUser = AV.User.current()
    var userId = currentUser.id
    var lessons = []

    var startDateQuery = new AV.Query('Favourite')
    var todoFolder = AV.Object.createWithoutData('User', userId);
    startDateQuery.equalTo('user', todoFolder)
    var endDateQuery = new AV.Query('Favourite');
    endDateQuery.equalTo('action', true)
    var query = AV.Query.and(startDateQuery, endDateQuery);
    query.find().then(function (result) {
      self.getRoles(function (role) {
        if (role) {
          //admin
          self.adminLike(result, lessons, function (list) {
            cb(list)
          })
        } else {
          //teacher

          self.teacherLike(result, lessons, function (list) {
            cb(list)
          })
        }
      })
    })
  },
  //admin的喜欢课程

  adminLike: function (result, lessons, cb) {
    var self = this
    result.forEach(function (item) {
      var lessonId = item.toJSON().lessonId
      var query = new AV.Query('Lesson')
      query.get(lessonId).then(function (todo) {
        var subject = todo._serverData.subject.id
        if (todo.toJSON().isChecked == 1) {
          //待审核
          self.getHistoryLesson(todo.id, function (result) {
            Vue.http.get(result).then(function (response) {
              var subject = response.data.subjectId
              lessons.push({
                'name': response.data.name,
                'id': response.data.id,
                'subject': self.judgeSubject(subject),
                'verstion': 'his'
              })
            })
          })
        }
        lessons.push({
          'name': todo.toJSON().name,
          'id': todo.id,
          'subject': self.judgeSubject(subject),
          'isChecked': todo.toJSON().isChecked
        })
      })
    })
    cb(lessons)
  },
  //老师的喜欢课程
  teacherLike: function (result, lessons, cb) {
    var self = this;
    result.forEach(function (item) {
      var lessonId = item.toJSON().lessonId
      var query = new AV.Query('Lesson')
      query.get(lessonId).then(function (todo) {
        if (todo.toJSON().isChecked == 1 || todo.toJSON().isChecked == 2) {
          self.getHistoryLesson(todo.id, function (result) {
            Vue.http.get(result).then(function (response) {
              var subject = response.data.subjectId
              lessons.push({
                'name': response.data.name,
                'id': response.data.id,
                'subject': self.judgeSubject(subject),
                'verstion': 'his'
              })
            })
          })
        } else {
          var subject = todo._serverData.subject.id
          lessons.push({'name': todo.toJSON().name, 'id': todo.id, 'subject': self.judgeSubject(subject)})
        }
      })
    })
    cb(lessons)
  },
  //检查喜欢
  checkoutLike: function (cb) {
    var self = this
    var currentUser = AV.User.current()
    var userId = currentUser.id
    var lessonIds = []
    var startDateQuery = new AV.Query('Favourite')
    var todoFolder = AV.Object.createWithoutData('User', userId);
    startDateQuery.equalTo('user', todoFolder)
    var endDateQuery = new AV.Query('Favourite');
    endDateQuery.equalTo('action', true)
    var query = AV.Query.and(startDateQuery, endDateQuery);
    query.find().then(function (result) {
      result.forEach(function (item) {
        lessonIds.push(item.toJSON().lessonId)
      })
      cb(lessonIds)
    })
  },
  //获取专题
  getSpecial: function (cb) {
    var self = this
    var specialLesson = {'allSpecial': [], 'recommend': []}
    var query = new AV.Query('SpecialSubject')
    query.equalTo('onLine', true)
    query.find().then(function (result) {
      result.forEach(function (item) {
        specialLesson.allSpecial.push(item.toJSON())
        if (item.toJSON().recommendStatus == true) {
          specialLesson.recommend.push(item.toJSON())
        }
      })
      cb(specialLesson)
    })
  },
  //获取专题课程
  getSpecialLesson: function (specialId, cb) {
    var self = this
    var allLesson = []
    var query = new AV.Query('LessonSpecial')
    var special = AV.Object.createWithoutData('SpecialSubject', specialId)
    query.equalTo('special', special)
    query.include('lesson')
    query.find().then(function (result) {
      result.forEach(function (item) {
        var lesson = item.toJSON().lesson
        if (lesson.isPublished === true && lesson.isChecked !== 1 && lesson.isChecked !== 2) {
          allLesson.push({
            'name': lesson.name,
            'id': lesson.objectId,
            'subject': self.judgeSubject(lesson.subject.objectId)
          })
        }
        if (lesson.isPublished === true && lesson.isChecked === 1 && lesson.isChecked === 2) {
          self.getHistoryLesson(lessonId, function (result) {
            Vue.http.get(result).then(function (response) {
              allLesson.push({
                'name': response.data.name,
                'id': response.data.id,
                'subject': self.judgeSubject(response.data.subjectId),
                'verstion': 'his'
              })
            })
          })
        }
      })
      cb(allLesson)
    })
  },
  //获取一个专题课程
  getOneSpection: function (specialId, cb) {
    var self = this
    var query = new AV.Query('SpecialSubject')
    query.get(specialId).then(function (result) {
      cb(result.toJSON())

    })
  },
  //getAllData
  getAllLessons: function (cb) {
    var self = this
    this.getRoles(function (result) {
      var subjects = []
      if (result === true) {
        self.getAdminSubLesson(subjects, function (result) {
          cb(result)
        })
      } else {
        self.getTeacherSubLesson(subjects, function (result) {
          cb(result)
        })
      }
    })
  },
  //获取管理员的lesson
  getAdminSubLesson: function (subjects, cb) {
    var self = this
    var priorityQuery = new AV.Query('Lesson');
    priorityQuery.equalTo('isPublished', true);
    var statusQuery = new AV.Query('Lesson');
    statusQuery.equalTo('isChecked', 1);
    var query = AV.Query.or(priorityQuery, statusQuery);
    query.find().then(function (result) {
      result.forEach(function (key) {
        var checkedStatus = key.attributes.isChecked
        subjects.push({
          'name': key.attributes.name,
          'id': key.id,
          'isChecked': checkedStatus,
          'tags': key.attributes.tags
        })
        if (checkedStatus == 1) {
          self.getHistoryLesson(key.id, function (result) {
            Vue.http.get(result).then(function (response) {
              subjects.push({
                'name': response.data.name,
                'id': response.data.id,
                'verstion': 'his',
                'tags': response.data.tags
              })
            })
          })
        }
      })
      cb(subjects)
    }, function (err) {
      console.log(err)
    })
  },
  //获取老师的全部科目课程
  //获取老师的全部课程
  getTeacherSubLesson: function (subjects, cb) {
    var self = this
    var query = new AV.Query('Lesson')
    query.equalTo('isPublished', true)


    query.find().then(function (result) {
      result.forEach(function (key) {
        if (key.attributes.isChecked === 3 || key.attributes.isChecked === 0) {
          subjects.push({'name': key.attributes.name, 'id': key.id})
        } else if (key.attributes.isChecked === 1 || key.attributes.isChecked === 2) {
          var lessonId = key.id
          self.getHistoryLesson(lessonId, function (result) {
            Vue.http.get(result).then(function (response) {
              subjects.push({'name': response.data.name, 'id': response.data.id, 'verstion': 'his'})
            }, function (err) {

            })
          })
        }
      })
      cb(subjects)
    }, function (err) {
      console.log(err)
    })
  },

  getLessonCountFromLeanCloud:function(filterCondition,getLessonCount){
    let lessonQuery = new AV.Query('Lesson');
    lessonQuery.descending('createdAt');
    lessonQuery.equalTo('isPublished', true);
    if (filterCondition.length > 0) {
      lessonQuery.containsAll('tags', filterCondition)
    }
    lessonQuery.count().then(function (count) {
      getLessonCount(count)
    }, function (error) {
    });
  },
  getLessonListCountWithNeedCheck:function(filterCondition,getLessonCount){
    let lessonQuery = new AV.Query('Lesson');
    lessonQuery.equalTo('isPublished', true);
    if (filterCondition.length > 0) {
      lessonQuery.containsAll('tags', filterCondition)
    }
    let needCheckLessonQuery = new AV.Query('Lesson');
    needCheckLessonQuery.equalTo('isChecked', 1);
    if (filterCondition.length > 0) {
      needCheckLessonQuery.containsAll('tags', filterCondition)
    }
    let query = AV.Query.or(lessonQuery, needCheckLessonQuery);
    query.descending('createdAt')
    query.count().then(function (count) {
      getLessonCount(count)
    }, function (error) {
    });
  },

  getLessonListWithTeacher: function (filterCondition,pageIndex, cb) {
    let lessonQuery = new AV.Query('Lesson');
    lessonQuery.descending('createdAt');
    lessonQuery.equalTo('isPublished', true);
    if (filterCondition.length > 0) {
      lessonQuery.containsAll('tags', filterCondition)
    }
    lessonQuery.limit(80);
    lessonQuery.skip((pageIndex-1)*80);
    lessonQuery.find().then((lessonList) => {
      let lessonListIds = lessonList.map(lesson => lesson.toJSON().objectId);
      let lessonInfoPromiseList = lessonList.map((key) => {
        key = key.toJSON()

        if (key.isChecked === 3 || key.isChecked === 0) {
          return new Promise(resolve => {
            return resolve({'name': key.name, 'id': key.objectId, coverImage: key.coverImage})
          })
        } else if (key.isChecked === 1 || key.isChecked === 2) {
          let lessonId = key.objectId;
          return new Promise(resolve => {
            this.getHistoryLesson(lessonId, function (result) {
              Vue.http.get(result).then(function (response) {
                console.log(response)
                return resolve({
                  'name': response.data.name,
                  'id': response.data.id,
                  'verstion': 'his',
                  coverImage: response.data.coverImage
                })
              }).catch(()=>resolve())
            })
          })
        }
      });

      Promise.all(lessonInfoPromiseList).then(lessonList => {
        console.log(lessonList.length)
        cb(lessonList)
      })
    })
  },

  getLessonListWithNeedCheck(filterCondition,pageIndex, getLessonList) {
    let self = this;
    let lessonQuery = new AV.Query('Lesson');
    lessonQuery.equalTo('isPublished', true);
    if (filterCondition.length > 0) {
      lessonQuery.containsAll('tags', filterCondition)
    }
    let needCheckLessonQuery = new AV.Query('Lesson');
    needCheckLessonQuery.equalTo('isChecked', 1);
    if (filterCondition.length > 0) {
      needCheckLessonQuery.containsAll('tags', filterCondition)
    }
    let query = AV.Query.or(lessonQuery, needCheckLessonQuery);
    query.descending('createdAt')
    query.limit(80);
    query.skip((pageIndex-1)*80);
    query.find().then(function (lessonList) {
      let lessonPromiseList = [];
      lessonList.forEach(function (lesson) {
        lesson = lesson.toJSON();
        let checkedStatus = lesson.isChecked;
        lessonPromiseList.push(new Promise(resolve => resolve({
          'name': lesson.name,
          'id': lesson.objectId,
          'isChecked': checkedStatus,
          'tags': lesson.tags,
          coverImage: lesson.coverImage
        })));
        if (checkedStatus === 1) {
          let historyLessonPromise = new Promise(resolve => {

            self.getHistoryLesson(lesson.objectId, function (historyLessonUrl) {
              console.log('======' + historyLessonUrl);
              if (!historyLessonUrl) return resolve()
              Vue.http.get(historyLessonUrl).then(function (historyLessonInfo) {
                console.log(historyLessonInfo)
                resolve({
                  'coverImage': historyLessonInfo.data.coverImage,
                  'name': historyLessonInfo.data.name,
                  'id': historyLessonInfo.data.id,
                  'verstion': 'his',
                  'tags': historyLessonInfo.data.tags
                })
              }, function (e) {
                console.log(e)
                resolve()
              })
            })
          })
          lessonPromiseList.push(historyLessonPromise)
        }
      });

      Promise.all(lessonPromiseList).then(function (lessonList) {
        getLessonList(lessonList.filter(lesson => lesson))
      }, function (e) {
        console.log(e)
      })
    }, function (err) {
      console.log(err)
    })
  },
  getLabels(type) {
    return new Promise(reslove => {
      new AV.Query('Label')
        .equalTo('type', type)
        .find().then((labelList) => {
        reslove(labelList.map(label => label.toJSON()))
      })
    })
  },
  getLikeLessonList(cb) {
    let self = this;
    let currentUser = AV.User.current();
    var lessons = [];
    var favouriteQuery = new AV.Query('Favourite');
    var todoFolder = AV.Object.createWithoutData('User', currentUser.id);
    favouriteQuery.equalTo('user', todoFolder);
    favouriteQuery.equalTo('action', true);
    favouriteQuery.find().then(function (favouriteList) {
      let promiseAll = [];
      favouriteList.forEach(function (item) {
        let lessonId = item.toJSON().lessonId;
        let lessonPromise = new Promise(resolve => {
          let lessonQuery = new AV.Query('Lesson');
          lessonQuery.get(lessonId).then(function (todo) {
            if (todo.toJSON().isChecked == 1 || todo.toJSON().isChecked == 2) {
              self.getHistoryLesson(todo.id, function (result) {
                Vue.http.get(result).then(function (response) {
                  var subject = response.data.subjectId
                  resolve({
                    'name': response.data.name,
                    'id': response.data.id,
                    'subject': self.judgeSubject(subject),
                    'verstion': 'his',
                    'coverImage': response.data.coverImage,
                  })
                })
              })
            } else {
              var subject = todo._serverData.subject.id
              resolve({'name': todo.toJSON().name, 'id': todo.id, 'subject': self.judgeSubject(subject),coverImage: todo.toJSON().coverImage,})
            }
          }).catch(() => {
            resolve()
          })
        })
        promiseAll.push(lessonPromise)
      })

      Promise.all(promiseAll).then(lessonList => {
        cb(lessonList.map(lesson => lesson))
      })
    })

  },
  getLikeLessonListNeedCheck(cb) {

    let self = this;
    let currentUser = AV.User.current();
    var favouriteQuery = new AV.Query('Favourite');
    var todoFolder = AV.Object.createWithoutData('User', currentUser.id);
    favouriteQuery.equalTo('user', todoFolder);
    favouriteQuery.equalTo('action', true);
    favouriteQuery.find().then(function (favouriteList) {

      let lessonIds = favouriteList.map(favourite => favourite.toJSON().lessonId)

        let lessonQuery = new AV.Query('Lesson');
        lessonQuery.containedIn('objectId', lessonIds)
        lessonQuery.find().then(function (lessonList) {
          let promiseAll = [];
          console.log(lessonList.length)
          lessonList.forEach(function(lesson){
            if (lesson.toJSON().isChecked === 1) {
              //待审核

              let lessonPromise = new Promise(resolve => {
                self.getHistoryLesson(lesson.id, function (result) {
                  Vue.http.get(result).then(function (response) {
                    let subject = response.data.subjectId;
                    resolve({
                      'name': response.data.name,
                      'id': response.data.id,
                      'subject': self.judgeSubject(subject),
                      'verstion': 'his',
                      coverImage: response.data.coverImage,
                    })
                  })
                })
              })
              promiseAll.push(lessonPromise);

            }
            promiseAll.push(new Promise(resolve => {return resolve({
              'name': lesson.toJSON().name,
              'id': lesson.id,
              'subject': self.judgeSubject(lesson._serverData.subject.id),
              'isChecked': lesson.toJSON().isChecked,
              coverImage: lesson.toJSON().coverImage,
            })}))
          });

          Promise.all(promiseAll).then(function(likeLessonList){
            cb(likeLessonList.map(lesson=>lesson))
          })

        },function(e){console.log(e)})
    }).catch(e=>{console.log(e)})
  }


}

